package dk.iha;

import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class SelectBTDeviceActivity extends ListActivity {
	
    BluetoothAdapter mBluetoothAdapter=null;
    BroadcastReceiver mReceiver = null;
	ArrayAdapter<String> debugDataAdapter = null;
	List<BluetoothDevice> devices = null;
	Button startSearchBtn;
	Button OKBtn;
	Button CancelBtn;
	ListView listView = null;
	int setSelPos=-1;

	
	
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.select_bt_device);
		
        startSearchBtn = (Button) findViewById(R.id.startSearchBTN);
		OKBtn = (Button) findViewById(R.id.okBTN);
		OKBtn.setEnabled(false);
		CancelBtn = (Button) findViewById(R.id.cancelBTN);

		listView = (ListView) findViewById(android.R.id.list);
		devices = new ArrayList<BluetoothDevice>();
		debugDataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1);
		setListAdapter(debugDataAdapter);

		//enable BT
		if(!checkAndEnableBTAdapter()){
			//device does not support BlueTooth
			return;
		}
		
		//StartSearch Button has been clicked
		startSearchBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				setupBT();
			}
		});
		
		//OKBtn Button has been clicked
		OKBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				//end discovery
		    	Log.w("WW","cancelDiscovery");
				mBluetoothAdapter.cancelDiscovery();
				
				//get the selected Bluetooth device
    	    	assert(setSelPos != -1);
				BluetoothDevice dev = devices.get(setSelPos);
    	    	Log.w("LIFETIME", "onListItemClick:"+setSelPos+" device:"+dev.getName());

    	    	//prepare return 
				Intent returnIntent = new Intent();
				returnIntent.putExtra("BTDevice", dev);
				setResult(RESULT_OK,returnIntent);     
				finish();				
			}
		});
		
		//Cancel Button has been clicked
		CancelBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				//end discovery
				mBluetoothAdapter.cancelDiscovery();

    	    	//prepare return 
				Intent returnIntent = new Intent();
				setResult(RESULT_CANCELED, returnIntent);        
				finish();
			}
		});
		
	}

	/**
	 * Called when user selects an entry in the list
	 * @param parent
	 * @param v
	 * @param pos
	 * @param id
	 */
    public void onListItemClick(ListView parent,View v,int pos,long id){    	
    	//listView.setSelection(pos);
    	Log.w("ww","onListItemClick");
    	setSelPos = pos;
    	if(pos >=0 && pos<devices.size()){
    		OKBtn.setEnabled(true);
    	}
    }    

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		Log.w("vv", "onActivityResult");
	     if (requestCode == 0) {
	     }
	 }

	
	
	private boolean checkAndEnableBTAdapter(){
    	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    	if (mBluetoothAdapter == null) {
    	    // Device does not support Bluetooth
    		Toast.makeText(this, "This device does not support Bluetooth!", Toast.LENGTH_LONG).show();
    		return false;
    	}
    	if (!mBluetoothAdapter.isEnabled()) {
    	    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    	    final int REQUEST_ENABLE_BT = 1;
    	    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    	}
    	return true;
	}

	/**
	 * Starts BlueTooth
	 */
    private void setupBT(){
    	//
    	//start discovery starts
    	//
    	// Create a BroadcastReceiver for ACTION_FOUND
    	mReceiver = new BroadcastReceiver() {
    	    public void onReceive(Context context, Intent intent) {
    	        String action = intent.getAction();
    	        // When discovery finds a device
    	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
    	            // Get the BluetoothDevice object from the Intent
    	            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    	            //if(device.getName().compareTo("BlackBox") == 0)
    	            //	mmDevice = device;
    	            // Add the name and address to an array adapter to show in a ListView
    	            String dev = device.getName() + " - " + device.getAddress();
    	            //mArrayAdapter.add(dev);
    	            //Toast.makeText(MainActivity.this, dev, Toast.LENGTH_SHORT).show();
    	            debugDataAdapter.add(dev);
    	    		debugDataAdapter.notifyDataSetChanged();
    	            devices.add(device);
    	        	Log.w("LIFETIME", "found device:"+dev);     
    	        }
    	    }
    	};
    	//mArrayAdapter=new ArrayList<String>();
    	// Register the BroadcastReceiver
    	IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    	registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
    	Log.w("WW","StartDiscovery");
    	mBluetoothAdapter.startDiscovery();
    	startSearchBtn.setEnabled(false);
    	//
    	//start discovery ends
    	//
    }

    @Override
    protected void onDestroy() {
		if(mReceiver != null)
			unregisterReceiver(mReceiver);
    	super.onDestroy();
    }
}
